package com.sxt.utils;

import java.util.BitSet;

public class BloomFilter {

	private int length = Integer.MAX_VALUE; //int = 4 byte * 8 = 32bit
	private BitSet bits = new BitSet() ;
	private int hashSize  = 4 ;
	private int [] seeds = new int[] {31,37,41,43};
	private HashFun[] hashFuncs = new HashFun[hashSize];
	{
		for (int i = 0; i < hashFuncs.length; i++) {
			hashFuncs[i] = new HashFun(seeds[i]) ;
		}
	}

	/**
	 * 将值放在位集合里面
	 * @param value
	 * @return
	 */
	public void set(String value) {
		System.out.println(value+"在位集合里面占的点为:");
		for (HashFun hashFun : hashFuncs) {
			/**
			 * 得到hash的值非常简单,因为我们只需要参考String的hashcode实现就可以了
			 * 但是通过hashcode得到该值到底映射在集合的那个位置上面,有点难度
			 */
			int hashCode = hashFun.hashCode(value);
			System.out.println("hashCode"+hashCode);
			int pos = (length-1) & hashCode  ;
			System.out.println("pos"+pos);
			bits.set(pos, true); // 将该点设置为1
		}
	}

	/**
	 * 判断位集合里面是否有该值
	 * @return
	 */
	public boolean isExist(String value) {
		for (HashFun hashFun : hashFuncs) {
			int hashCode = hashFun.hashCode(value);
			int pos = (length-1) & hashCode ;
			if(!bits.get(pos)) {
				return false ;
			}
		}
		return true;
	}
	public static void main(String[] args) {
		BloomFilter bloomFilter = new BloomFilter();
		bloomFilter.set("mayun");
		bloomFilter.set("mayul");
		bloomFilter.set("moyun");
		bloomFilter.set("mayue");
		bloomFilter.set("maynn");

		if(bloomFilter.isExist("mayui")) {
			System.out.println("mayuiok"); //false
		}

		if(bloomFilter.isExist("mayun")) {
			System.out.println("mayunok");// true
		}

		if(bloomFilter.isExist("maynn")) {
			System.out.println("maynnok"); //true
		}
	}
}
